import { useState } from "react";
import { View, Text, Input, Button } from "@tarojs/components";
import Taro, { useLoad, useDidShow } from "@tarojs/taro";
import { request } from "../../api/request";
import { apis } from "../../api/api";
import "./index.scss";

export default function Index() {
  const [name, setName] = useState<string | undefined>(undefined);
  const [psw, setPsw] = useState<string | undefined>(undefined);
  useLoad(() => {
    console.log("Page loaded.");
    Taro.hideHomeButton();
  });
  useDidShow(() => {
    console.log("Page show.");
    // Taro.hideHomeButton();
  });
  const login = async () => {
    Taro.showLoading({
      title: "加载中",
    });
    let result = await request(
      "post",
      apis.login,
      { username: name, password: psw },
      false
    );
    console.log("result+++", result);
    if (result?.success) {
      Taro.setStorage({ key: "token", data: result.data });
      Taro.hideLoading();
      Taro.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1500,
      });
      Taro.switchTab({
        url: "/pages/main/index",
      });
    } else {
      Taro.hideLoading();
      Taro.showToast({
        title: "登录失败",
        icon: "error",
        duration: 1500,
      });
    }
  };

  return (
    <View className="login-container">
      <View>
        <View className="title">智能基坑监测预警系统</View>
        <View className="input-line">
          <Text>账号</Text>
          <Input
            type="text"
            placeholder="请输入账号"
            className="input"
            onInput={(e) => {
              setName(e.detail.value);
            }}
          />
        </View>
        <View className="input-line">
          <Text>密码</Text>
          <Input
            type="text"
            password
            placeholder="请输入密码"
            className="input"
            onInput={(e) => {
              setPsw(e.detail.value);
            }}
          />
        </View>
        <View className="login-btn">
          <Button
            size="default"
            className="btn"
            onTap={() => {
              login();
            }}
          >
            登录
          </Button>
        </View>
      </View>
    </View>
  );
}
